package com.oritsh.dicom.wado.service;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


/**
 * Created by xiashenpin on 15/7/19.
 */
public class HTTPDicomGet {
    String rootURL;


    public String getRootURL() {
        return rootURL;
    }

    public void setRootURL(String rootURL) {
        this.rootURL = rootURL;
    }

    public InputStream cget(String uid) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        try (CloseableHttpClient httpclient = HttpClients.createDefault() ) {
            String totalURL = rootURL + uid;

            HttpGet httpget = new HttpGet(totalURL);

            HttpClientContext context = new HttpClientContext();

            try (CloseableHttpResponse response = httpclient.execute(httpget, context)) {
                HttpEntity entity = response.getEntity();
                outputStream.write(EntityUtils.toByteArray(entity));
            }
        }

        return new ByteArrayInputStream(outputStream.toByteArray());
    }
}
